package com.elitel.frame.web.serverinfo.controller;


import com.elitel.frame.web.serverinfo.dto.TestSimApiDTO;
import com.google.gson.Gson;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 模拟请求
 */
@RestController
@RequestMapping("testSimApi")
public class TestSimApiController {

    private static final String CONTENT_TYPE = "Content-Type";
    private static final String APPLICATION_JSON = "application/json";
    /**
     * 模拟请求
     * @param testSimApiDTO
     * @return
     */
    @RequestMapping("/request")
    public Object request(@RequestBody TestSimApiDTO testSimApiDTO) {
        String url = testSimApiDTO.getUrl();
        Map<String, String> headers = testSimApiDTO.getHeaders();
        Map<String, String> body = testSimApiDTO.getBody();
        String method = testSimApiDTO.getMethod();
        Object result;
        if ("GET".equalsIgnoreCase(method)) {
            try {
                result = sendRequestWithHttpClient(url, "GET", headers, body);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if ("POST".equalsIgnoreCase(method)) {
            try {
                result = sendRequestWithHttpClient(url, "POST", headers, body);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            throw new IllegalArgumentException("Unsupported HTTP method: " + method);
        }
        return result;
    }


    // 使用Apache HttpClient发送请求
    private String sendRequestWithHttpClient(String url, String method, Map<String, String> headers, Map<String, String> body) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpUriRequest request;
            if ("GET".equalsIgnoreCase(method)) {
                // 对于GET请求，如果带有body，需要特殊处理
                if (body != null && !body.isEmpty()) {
                    HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(url);
                    String jsonBody = new Gson().toJson(body);
                    StringEntity entity = new StringEntity(jsonBody, StandardCharsets.UTF_8);

                    // 设置Content-Type
                    String contentType = APPLICATION_JSON;
                    if (headers != null && headers.containsKey(CONTENT_TYPE)) {
                        contentType = headers.get(CONTENT_TYPE);
                    }
                    entity.setContentType(contentType);

                    httpGetWithEntity.setEntity(entity);
                    request = httpGetWithEntity;
                } else {
                    // 普通GET请求
                    HttpGet httpGet = new HttpGet(url);
                    request = httpGet;
                }
            } else {
                HttpPost httpPost = new HttpPost(url);
                if (body != null && !body.isEmpty()) {
                    String jsonBody = new Gson().toJson(body);
                    StringEntity entity = new StringEntity(jsonBody, StandardCharsets.UTF_8);
                    entity.setContentType(headers.get(CONTENT_TYPE));
                    httpPost.setEntity(entity);
                }
                request = httpPost;
            }

            // 设置请求头
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    request.setHeader(entry.getKey(), entry.getValue());
                }
            }

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            }
        }
    }

    /**
     * 自定义HttpGet请求类，用于处理带有body的GET请求
     */
    class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
        public final static String METHOD_NAME = "GET";

        public HttpGetWithEntity() {
            super();
        }

        public HttpGetWithEntity(final URI uri) {
            super();
            setURI(uri);
        }

        public HttpGetWithEntity(final String uri) {
            super();
            setURI(URI.create(uri));
        }

        @Override
        public String getMethod() {
            return METHOD_NAME;
        }
    }

    //模拟get 请求, post 请求，带有param 和 body 的4种场景，
    @GetMapping("/getBody")
    public Object getBody(@RequestBody Map<String, Object> testSimApiDTO, HttpServletRequest request) {
        testSimApiDTO.put("function", "getBody");
        testSimApiDTO.put("head", request.getHeader("TOKEN"));
        testSimApiDTO.put("requestParam", request.getParameterMap());
        return testSimApiDTO;
    }

    @PostMapping("/postBody")
    public Object postBody(@RequestBody Map<String, Object> testSimApiDTO, HttpServletRequest request) {
        testSimApiDTO.put("function", "postBody");
        testSimApiDTO.put("head", request.getHeader("TOKEN"));
        testSimApiDTO.put("requestParam", request.getParameterMap());
        return testSimApiDTO;
    }

    @GetMapping("/getWithoutBody")
    public Object getWithoutBody(@RequestParam Map<String, Object> testSimApiDTO, HttpServletRequest request) {
        testSimApiDTO.put("function", "getWithoutBody");
        testSimApiDTO.put("head", request.getHeader("TOKEN"));
        testSimApiDTO.put("requestParam", request.getParameterMap());
        return testSimApiDTO;
    }

    @PostMapping("/postWithoutBody")
    public Object postWithoutBody(@RequestParam Map<String, Object> testSimApiDTO, HttpServletRequest request) {
        testSimApiDTO.put("function", "postWithoutBody");
        testSimApiDTO.put("head", request.getHeader("TOKEN"));
        testSimApiDTO.put("requestParam", request.getParameterMap());
        return testSimApiDTO;
    }
}
